//!
//! Copyright (c) 2024-2999 北京心月狐科技有限公司 All rights reserved.
//!
//! https://www.mxxshop.com
//!
//! Licensed 并不是自由软件，未经许可不能去掉 MxxShop 相关版权
//!
//! 版权所有，侵权必究！
//!

use std::fs;
use std::io::Read;
use std::path::Path;
use actix_files::{Files as ActixFiles};
use actix_web::{get, web, HttpResponse, Responder};

use crate::modules::articles::controller::open::article_open_controller;
use crate::modules::statistics::controller::open::statistics_open_controller;
use crate::modules::system::controller::open::{captcha_controller, index_open_controller, service_open_controller};
use crate::modules::user::controller::open::user_open_controller;

/// 静态文件服务
#[get("/static/{filepath:.*}")]
async fn serve_static(filepath: web::Path<String>) -> crate::core::errors::error::Result<impl Responder> {
    let path = Path::new("./static").join(filepath.into_inner());
    if path.is_file() {
        let mut file = fs::File::open(path)?;
        let mut buf = Vec::new();
        file.read_to_end(&mut buf)?;
        Ok(HttpResponse::Ok().body(buf))
    } else {
        Ok(HttpResponse::NotFound().body("Custom 404 Not Found"))
    }
}

pub fn configure_routes(cfg: &mut web::ServiceConfig) {
    cfg
        .service(serve_static)
        .service(ActixFiles::new("/upload/", "storage/upload/").show_files_listing())
        .service(index_open_controller::index) //首页
        .service(web::resource("/service/privacy").route(web::get().to(service_open_controller::service_privacy)))
        .service(web::resource("/service/faq").route(web::get().to(service_open_controller::service_faq)))
        .service(web::resource("/service/contacts").route(web::get().to(service_open_controller::service_contacts)))
        .service(web::resource("/a-list/{category}").route(web::get().to(article_open_controller::article_list)))
        .service(web::resource("/a-list/{category}/{page}").route(web::get().to(article_open_controller::article_list)))
        .service(article_open_controller::article_detail)
        .service(web::resource("/u/{short_url}/").route(web::get().to(user_open_controller::user_index)))
        .service(captcha_controller::get_captcha)
        .service(statistics_open_controller::save_statistics_record)
    ;
}